<template>
  <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="账户" prop="username">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入账户"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5" v-if="$store.state.currentJur.isAdd">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <!--<el-col :span="1.5" v-if="$store.state.currentJur.isEdit">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5" v-if="$store.state.currentJur.isDel">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>-->
        </el-row>

        <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="账户" align="center" key="Account" prop="Account" width="100"  />
          <el-table-column label="账户" align="center" key="UserName" prop="UserName" :show-overflow-tooltip="true"  width="150" />
          <el-table-column label="角色名称" align="center" key="RoleName" prop="RoleName" :show-overflow-tooltip="true"  width="100" />
          
          <el-table-column label="所属单位" align="center" key="CompanyName" prop="CompanyName" :show-overflow-tooltip="true"  width="100" />
          
          <el-table-column label="所属小组" align="center" key="GroupName" prop="GroupName" width="120" />
          <el-table-column label="创建时间" align="center" key="CreateTime" prop="CreateTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.CreateTime) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="状态" align="center" key="Stats">
            <template slot-scope="scope">
            <el-link :underline="false" :type="scope.row.Stats==1?'success':'danger'">{{scope.row.Stats?'启用':'禁用'}}</el-link>
              <!--<el-switch
                v-model="scope.row.Stats"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>-->
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="180"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button v-if="$store.state.currentJur.isEdit"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button v-if="$store.state.currentJur.isDel"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
              <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-if="$store.state.currentJur.isResetPass">
                <span class="el-dropdown-link">
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="handleResetPwd" icon="el-icon-key"
                    >重置密码</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
         <!-- 添加或修改用户配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
            <el-col :span="12">
                <el-form-item label="账户" prop="account">
                <el-input :disabled="title=='修改用户'?true:false" v-model="form.account" placeholder="请输入账户" maxlength="30" />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="用户昵称" prop="username">
                <el-input v-model="form.username" placeholder="请输入用户昵称" maxlength="30" />
                </el-form-item>
            </el-col>
            
            <el-col :span="12" v-if="title != '修改用户'">
                <el-form-item label="用户密码" prop="password">
                <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password/>
                </el-form-item>
            </el-col>
            
            <el-col :span="12">
                <el-form-item label="角色" prop="role">
                <el-select v-model="form.role" placeholder="请选择角色" multiple>
                    <el-option
                    v-for="item in roleOptions"
                    :key="item.ID"
                    :label="item.Name"
                    :value="item.ID"
                    ></el-option>
                </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="所属单位" prop="company">
                    <el-select v-model="form.company" placeholder="请选择单位">
                        <el-option
                        v-for="item in companyOptions"
                        :key="item.ID"
                        :label="item.Name"
                        :value="item.ID"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="职位" prop="position">
                  <el-select v-model="form.position" placeholder="请选择职位" @change="positionChange">
                    <el-option
                    v-for="item in positionOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    ></el-option>
                </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12" v-if="isGroup">
                <el-form-item label="所属小组" prop="group">
                 <!--<treeselect v-model="form.group" :options="groupOptions" :show-count="true" placeholder="请选择所属小组" />-->
                    <el-select v-model="form.group" placeholder="请选择小组">
                        <el-option
                        v-for="item in groupOptions"
                        :key="item.ID"
                        :label="item.Name"
                        :value="item.ID"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="状态" prop="Status">
                  <el-select v-model="form.Status" placeholder="请选择">
                    <el-option :key="1" label="启用" :value="1"></el-option>
                    <el-option :key="0" label="禁用" :value="0"></el-option>
                </el-select>
                </el-form-item>
            </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
        </el-dialog>
</div>
</template>
<script>
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    export default {
        name: 'user_manage',
        components: { Treeselect },
        data() {
            return {
                // 查询参数
                queryParams: {
                    page: 1,
                    pageSize: 10,
                    username: '',
                },
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                dateRange: [],
                //  表单参数
                form: {},
                // 总条数
                total: 0,
                // 用户表格数据
                tableData: null,
                // 弹出层标题
                title: "",
                open: false,
                companyOptions:[],groupOptions:[],
                roleOptions:[],
                //  职位
                isGroup: true,
                positionOptions:[{
                  id:1,
                  name: '总公司经理'
                },{
                  id:2,
                  name: '主管'
                },{
                  id:3,
                  name: '面试官'
                },{
                  id:4,
                  name: '人事'
                },{
                  id:5,
                  name: '驻场'
                }],
                 // 表单校验

                rules: {
                    account: [
                    { required: true, message: "账户不能为空", trigger: "blur" },
                    { min: 2, max: 20, message: '账户长度必须介于 2 和 20 之间', trigger: 'blur' }
                    ],
                    username: [
                    { required: true, message: "用户昵称不能为空", trigger: "blur" }
                    ],
                    password: [
                    { required: true, message: "用户密码不能为空", trigger: "blur" },
                    // { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
                    ],
                    role: [
                    { required: true, message: "角色不能为空", trigger: "change" }
                    ],
                    company: [
                    { required: true, message: "所属单位不能为空", trigger: "change" }
                    ],
                    group: [
                    { required: true, message: "所属小组不能为空", trigger: "change" }
                    ],
                    position: [
                    { required: true, message: "职位不能为空", trigger: "change" }
                    ],
                    Status: [
                    { required: true, message: "状态不能为空", trigger: "change" }
                    ],
                    // email: [
                    // {
                    //     type: "email",
                    //     message: "请输入正确的邮箱地址",
                    //     trigger: ["blur", "change"]
                    // }
                    // ],
                    // phonenumber: [
                    // {
                    //     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                    //     message: "请输入正确的手机号码",
                    //     trigger: "blur"
                    // }
                    // ]
                },
            }
        },
        created() {
            this.getList();
            this.getRole();
            this.getCompony();
            this.getGroup();
        },
        methods: {
          //  更改职位
          positionChange(val) {
            console.log(val)
            if(val==1) {
              this.form.group = 0;
              this.isGroup = false;
            } else {
              this.form.group = '';
              this.isGroup = true;
            };
            
          },
            handleQuery() {
                this.queryParams.page = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.dateRange = [];
                this.resetForm("queryForm");
                this.handleQuery();
            },
            //  角色
            getRole() {
              this.$http.get(this.GLOBAL.REQUESTURL+"/api/role?page=1&pageSize=100&name=")
              .then(res=>{
                this.roleOptions = res.data.roleList;
              }).catch(err=>{

              })
            },
            //  所属单位
            getCompony() {
              const self_ = this;
              this.$http.get(this.GLOBAL.REQUESTURL+"/api/company?page=1&pageSize=100&name=")
                .then(res=>{
                    self_.companyOptions = res.data.comlist;
                }).catch(err=>{

                })
            },
            //  所属小组
            getGroup() {
              const self_ = this;
              this.$http.get(this.GLOBAL.REQUESTURL+"/api/group?page=1&pageSize=100&name=")
                .then(res=>{
                    self_.groupOptions = res.data.grouplist;
                }).catch(err=>{

                })
            },
            getList() {
                const this_ = this
                this_.$http.get(this_.GLOBAL.REQUESTURL + "/api/users", {
                  page: this_.queryParams.page,
                  pageSize: this_.queryParams.pageSize,
                  username: this_.queryParams.username,
                })
                .then(res => {
                    this_.tableData = res.data.userlist; //给查询列表赋值
                    this_.total = res.data.total;
                    this_.loading = false;
                })
                .catch(function(err) {
                    this_.tableData = [];
                    this_.total = 0;
                    this_.loading = false;
                });

            },
            /***更多操作*/
            handleCommand(command, row) {
              switch (command) {
                case "handleResetPwd":
                  this.handleResetPwd(row);
                  break;
                default:
                  break;
              }
            },
            /** 重置密码按钮操作 */
            handleResetPwd(row) {
              const _self = this;
              // this.$prompt('请输入"' + row.UserName + '"的新密码', "提示", {
              //   confirmButtonText: "确定",
              //   cancelButtonText: "取消",
              //   closeOnClickModal: false,
              //   inputPattern: /^.{5,20}$/,
              //   inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
              // }).then(({ value }) => {
              //     _self.$http.patch(_self.GLOBAL.REQUESTURL+"/api/resetting/"+row.ID).then(res=>{
              //        _self.$modal.msgSuccess("修改成功，新密码是：" + value);
              //     })
              //   }).catch(() => {});
              this.$modal.confirm('确认要重置"' + row.UserName + '"密码吗？').then(function() {
                    // return changeUserStatus(row.userId, row.status);
                }).then(() => {
                  _self.$http.patch(_self.GLOBAL.REQUESTURL+"/api/resetting/"+row.ID).then(res=>{
                     _self.$modal.msgSuccess("重置成功，新密码是：123456");
                  })
                    //this.$modal.msgSuccess( "重置成功");
                }).catch(function() {
                    //this.$modal.msgWarning( "重置失败");
                });
            },
            handleAdd() {
                this.reset();
                this.title = "添加用户";
                this.open = true;
                this.form.password = '';
            },
             /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                this.open = true;
                this.title = "修改用户";
                this.form.password = "";
                this.form.editId = row.ID || this.ids;
                this.$http.get(this.GLOBAL.REQUESTURL+"/api/users/"+this.form.editId)
                .then(res=>{
                  console.log(res)
                  this.form.account = res.data.Account;
                  this.form.username = res.data.UserName;
                  this.form.password = res.data.password;
                  this.form.role = res.data.RoleId;
                  this.form.company = res.data.CompanyId;
                  this.form.group = res.data.GroupId;
                  this.form.position = res.data.PositionId;
                  this.form.Status = res.data.Stats;
                  this.isGroup = res.data.PositionId==1?false:true;
                }).catch(err=>{

                })
            },
            handleDelete1(row) {
                this.$modal.confirm('确认要删除"' + row.username + '"用户吗？').then(function() {
                    // return changeUserStatus(row.userId, row.status);
                }).then(() => {
                    this.$modal.msgSuccess( "删除成功");
                }).catch(function() {
                    //this.$modal.msgWarning( "删除失败");
                });
            },
            handleDelete(row) {
                const _self = this;
                const delIds = row.ID || this.ids;
                this.$modal.confirm('确认要删除"' + row.UserName + '"吗？').then(function() {
                   _self.$http.deleteFn(_self.GLOBAL.REQUESTURL+"/api/users/"+row.ID).then(res=>{
                        _self.$modal.msgSuccess( "删除成功");
                        _self.queryParams.page = 1;
                        _self.getList();
                    }).catch(function() {
                        //_self.$modal.msgWarning( "删除失败");
                    });  
                }).catch(function() {
                    // _self.$modal.msgWarning( "删除失败");
                });
            },
            submitForm: function() {
              const _this = this
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.editId != undefined) {
                            _this.$http.put(_this.GLOBAL.REQUESTURL+"/api/users/"+_this.form.editId,{
                              username: _this.form.username,
                              role: _this.form.role,
                              company:_this.form.company,
                              position:_this.form.position,
                              group:_this.form.group,
                              Status:_this.form.Status
                            })
                            .then(res => {
                              console.log(res)
                              if(res.code == 200) {
                                _this.$modal.msgSuccess( res.msg );
                              } else {
                                _this.$modal.msgWarning( res.msg );
                              }
                              _this.open = false;
                              _this.getList();
                            }).catch(err => {
                              //_this.$modal.msgError('修改失败!');
                            })
                        } else {
                            _this.$http.post(_this.GLOBAL.REQUESTURL+"/api/users",_this.form)
                            .then(res => {
                                if(res.code==200){
                                    _this.$modal.msgSuccess(res.msg);
                                } else {
                                    _this.$modal.msgWarning(res.msg);
                                }
                                _this.open = false;
                                _this.getList();
                            }).catch(err=> {
                               //_this.$modal.msgError('新增失败!');
                            })
                        }
                    }
                })
            },
            handleExport() {},
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.ID);
                this.single = selection.length != 1;
                this.multiple = !selection.length;
            },
             // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 用户状态修改
            handleStatusChange(row) {
                let text = row.status === "0" ? "启用" : "停用";
                this.$modal.confirm('确认要"' + text + '""' + row.UserName + '"用户吗？').then(function() {
                    // return changeUserStatus(row.userId, row.status);
                }).then(() => {
                    this.$modal.msgSuccess(text + "成功");
                }).catch(function() {
                    row.status = row.status === "0" ? "1" : "0";
                });
            },
             // 表单重置
            reset() {
                this.form = {
                    editId: undefined,
                    account: undefined,
                    username: undefined,
                    password: undefined,
                    Status: undefined,
                    role: [],
                    company:[],
                    position: [],
                    group: '',
                };
                this.resetForm("form");
            },
        }
    }
</script> 